const express = require('express');
const sessions = require('express-sessions');
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended: true}));
const router = express.Router()

const username_DB = 'Katrina';
const password_DB = 'katrinasayhello';
var session_DB;

// @ts-ignore
app.use(sessions({
    secret: 'Katrina的签名',  // 给session ID cookie签名
    name: 'Beautiful Katrina',  // 默认是connect.sid
    cookie: {maxAge: 1500},   // 有效期
    resave: false, 
    saveUninitialized: false,   // 这里设置为false 说明除非会话被修改 否则不会在浏览器上设置cookie
}));


app.get('/', (req, res) => {
    console.log('用户保存了页面');
    session_DB = req.session;
    if (session_DB.username) {
        res.send(
            `
                <h1>欢迎你来，${session_DB.username}</h1>
                <a href='/logout'>登出</a>
            `
        );
    } else {
        res.sendFile(_dirname + '/index.html');
    };
});


app.get('/login', (req, res) => {
    if (req.body.username === username_DB && req.body.password === password_DB) {
        session_DB = req.session;
        session_DB.username = req.body.username;
        console.log('服务器生成新的Session对象');
        console.log(req.session);
        console.log(`当前的唯一对话ID，藏在cookie里面的value：${req.sessionID}`);
        res.send(
            `
                <h1>欢迎你来，${session_DB.username}</h1>
                <a href='/logout'>登出</a>
            `
        );
    } else {
        res.send('用户名或者密码--错误');
    };
});

app.get('/logout', (req, res) => {
    req.session.destroy();   // 清除服务器session
    console.log(`用户登出网页后，当前服务器的session的内容为：${req.session}`);
    res.redirect('/');
});


app.listen('3838', () => console.log('3838 runing!'))



module.exports = app;


